package com.tony.controller;

import com.tony.lock.DistributedLockHandler;
import com.tony.lock.Lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/lock")
public class LockController {

    @Autowired
    private DistributedLockHandler distributedLockHandler;

    // http://localhost:8010/lock/lock1?name=1&value=test1&min=13
    // http://localhost:8010/lock/lock1?name=1&value=test2&min=13
    @RequestMapping("/lock1")
    public String lock(String name,String value ,int min) throws InterruptedException {
        String res = null;
        Calendar calendar = Calendar.getInstance();
        while(calendar.get(Calendar.MINUTE)<min) {
            calendar = Calendar.getInstance();
        }

        System.out.println("do.........."+new Date().getTime()+"v:"+value);
        Lock lock = new Lock(name,value);
        if (distributedLockHandler.tryLock(lock)) {
            Thread.sleep(100);
            res = value + " 开始执行";
            distributedLockHandler.releaseLock(lock);
        } else {
            res = value + " 执行中";
        }
        return res;
    }
}

